// pages/orderPay/orderPay.js
import {
  Get,
  Post,
  JsonPost
} from "../../utils/request.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    wpxIos: false,
    // 支付完成
    payed: false,
    // 默认收货地址
    adInfo: '',
    goodsInfo: '',
    totalPric: 0,
    paying: false,
    // 支付成功与否
    paySuccess: false,
    options: null,
    peiSarr:[
      {
        id: 1,
        name: '市区站点(送至离您最近的站点后会联系您前往自提)'
      },
      {
        id: 2,
        name: '门店自提(请选择离您最近的门店提货)'
      },
      {
        id: 3,
        name: '送货上门(仅送货上门,安装需另选服务)'
      }
    ],
    peiSname:null,
    peiSid:null,
    // 是否购物车
    ifCart:false,
    // 留言
    message:null,
    // 拼单id
    pingou_id:null,
    bargaining_id:null,
    invoice_id:null,
    // 选中门店
    storeInfo:null,
    // 可使用优惠券数量
    coupNum:null,
    couponInfo:{},
    // 订单是否含岩板
    ifYan:false,
    // 岩板木架费
    stake_price:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      options,
      wpxIos: getApp().globalData.wpxIos,
      goodsInfo: getApp().globalData.shopCartInfo,
      peiSname:'市区站点',
      peiSid:1,
      ifCart:options.ifCart,
      pingou_id:options.pinId,
      bargaining_id:options.bargaining_id,
    })
    this.data.goodsInfo.forEach(ele => {
      if (ele.cateName=='岩板') {
        this.setData({
          ifYan:true
        })
      }
    });
  },

  bindPickerChange(e){
    let num=Number(e.detail.value)
    this.setData({
      peiSname:this.data.peiSarr[num].name,
      peiSid:this.data.peiSarr[num].id,
    })
    this.wpxjisuan()
  },

  wpxjisuan(){
    wx.showLoading({
      title: '计算金额中',
    })
    let obj={
      'distribute_type':this.data.peiSid,
      'pingou_id':this.data.pingou_id,
      'bargaining_id':this.data.bargaining_id,
      'coupons_id':this.data.couponInfo.id,
      'data':this.data.goodsInfo
    }
    JsonPost('order/pay-price',obj).then(res=>{
      this.setData({
        goods_price:res.data.goods_price,
        pay_price:res.data.pay_price,
        service_price:res.data.service_price,
        stake_price:res.data.stake_price,
      })
      this.getCoupon()
      wx.hideLoading()
    })
  },

    //减
    reduce: function(e) {
      let str='goodsInfo['+e.currentTarget.dataset.index+'].num'
      var day_number = this.data.goodsInfo[e.currentTarget.dataset.index].num;
      if (1 < day_number) {
        day_number--;
      } else {
        day_number = 1;
      }
      this.setData({
        [str]: day_number
      })
      this.wpxjisuan()
    },
    //加
    add: function(e) {
      let str='goodsInfo['+e.currentTarget.dataset.index+'].num'
      var day_number = this.data.goodsInfo[e.currentTarget.dataset.index].num;
      day_number++;
      this.setData({
        [str]: day_number
      })
      this.wpxjisuan()
    },

    setNum(e){
      let ind = e.target.dataset.index;
      let num=Number(e.detail.value)
      var str = "goodsInfo[" + ind + "].num"
      if (num<1) {
        this.setData({
          [str]:1
        })
      }else{
        this.setData({
          [str]:num
        })
      }
      this.wpxjisuan()
    },


  // 支付
  goPay() {
    if (!this.data.adInfo) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none',
        duration: 2000
      })
      return
    }
    // if (!this.data.shop_id&&this.data.peiSid==2) {
    //   wx.showToast({
    //     title: '请选择提货门店',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return
    // }
    if (this.data.paying) return
    wx.showLoading({
      title: '发起支付中',
    })
    this.setData({
      paying: true
    })
    let order_sn=null
    if (this.data.ifCart=='true') {
      let data={
        'distribute_type':this.data.peiSid,
        'address_id':this.data.adInfo.id,
        'shop_id':this.data.shop_id,
        'message':this.data.message,
        'coupons_id':this.data.couponInfo.id,
        'data':this.data.goodsInfo,
        'pingou_id':this.data.pingou_id,
        'bargaining_id':this.data.bargaining_id,
        'invoice_id':this.data.invoice_id,
      }
      JsonPost('order/generateCat',data).then(res=>{
        order_sn=res.data.order_sn
        this.wxPay(order_sn)
      })
      
    }else{
      let data={
        'distribute_type':this.data.peiSid,
        'address_id':this.data.adInfo.id,
        'shop_id':this.data.shop_id,
        'message':this.data.message,
        'coupons_id':this.data.couponInfo.id,
        'goods_id':this.data.goodsInfo[0].goods_id,
        'spec_id':this.data.goodsInfo[0].spec_id,
        'num':this.data.goodsInfo[0].num,
        'paving_service_id':this.data.goodsInfo[0].paving_service_id,
        'machining_service_id':this.data.goodsInfo[0].machining_service_id,
        'machining_num':this.data.goodsInfo[0].machining_num,
        'pingou_id':this.data.pingou_id,
        'bargaining_id':this.data.bargaining_id,
        'invoice_id':this.data.invoice_id,
      }
      JsonPost('order/generate',data).then(res=>{
        order_sn=res.data.order_sn
        this.wxPay(order_sn)
      })
    }
  },

  // 调起微信支付
  wxPay(e){
    let that=this
    JsonPost('payment/wxPay',{'order_sn':e}).then(Pes=>{
      wx.hideLoading()
      wx.requestPayment({
        timeStamp: Pes.data.timeStamp,
        nonceStr: Pes.data.nonceStr,
        package: Pes.data.package,
        signType: 'MD5',
        paySign: Pes.data.paySign,
        success(res) {
          console.log(res, 'success')
          that.setData({
            paying: false,
          })
          let arr=[]
          that.data.goodsInfo.forEach(ele => {
            arr.push({
              img:ele.img,
              goods_name:ele.goods_name,
              color:ele.color,
              size:ele.size,
              num:ele.num,
            })
          });
          wx.navigateTo({
            url: '/pages/paySucess/paySucess?goodsInfo='+JSON.stringify(arr)+'&pingou_id='+that.data.pingou_id+'&order_sn='+e+'&price='+that.data.pay_price,
          })
        },
        fail(res) {
          console.log(res, 'fail')
          that.setData({
            paying: false,
          })
          wx.showToast({
            title: '支付失败',
            icon: 'none',
            duration: 2000
          })
        }
      })
    })
  },


  getCoupon(){
    let goods_id=''
    this.data.goodsInfo.forEach((ele,index) => {
      goods_id=goods_id+ele.goods_id+(index==(this.data.goodsInfo.length-1)?'':',')
    });
    let data={
      goods_id,
      type:1,
      price:this.data.goods_price,
      delivery_service_id:this.data.peiSid,
    }
    JsonPost('coupons/list',data).then(res=>{
      this.setData({
        coupNum:res.data.length
      })
    })
  },

  goCoupon(){
    let goods_id=''
    this.data.goodsInfo.forEach((ele,index) => {
      goods_id=goods_id+ele.goods_id+(index==(this.data.goodsInfo.length-1)?',':'')
    });
    let data={
      goods_id,
      type:1,
      price:this.data.goods_price,
      delivery_service_id:this.data.peiSid,
    }
    wx.navigateTo({
      url: '/pages/coupList/coupList?goods_id='+goods_id+'&price='+data.price+'&delivery_service_id='+data.delivery_service_id,
    })
  },

  // 前往地址选择
  goAdress() {
    wx.navigateTo({
      url: '/pages/adress/adress?pay=true'
    })
  },

  // 前往门店选择
  goStore() {
    wx.navigateTo({
      url: '/pages/storeList/storeList?pay=true'
    })
  },

    
  setValue(e) {
    let str = e.currentTarget.dataset.row
    this.setData({
      [str]: e.detail.value
    })
  },

  // 前往订单
  goOrder() {
    wx.redirectTo({
      url: '/pages/myOder/myOder?action=0'
    })
  },

  // 前往发票
  goInvoice() {
    wx.navigateTo({
      url: '/pages/invoice/invoice'
    })
  },

  // 继续逛逛
  goOn() {
    wx.navigateBack({
      delta: 2
    })
  },

  // 重新支付
  tooPay() {
    this.setData({
      payed: false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  
  getAdress(){
    JsonPost('user/address-list').then(res=>{
      this.setData({
        adInfo: res.data[0]
      })
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (getApp().globalData.adressInfo) {
      this.setData({
        adInfo:getApp().globalData.adressInfo
      })
    }else{
      this.getAdress()
    }
    this.setData({
      storeInfo:getApp().globalData.storeInfo,
      invoice_id:getApp().globalData.invoice_id,
    })
    this.setData({
      couponInfo:getApp().globalData.couponInfo,
    })
    console.log(this.data.couponInfo);
    
    this.wpxjisuan()
    this.setData({
      shop_id:getApp().globalData.storeInfo.id,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    getApp().globalData.shopCartInfo=[]
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})